package com.wh.demo_test;

import java.util.concurrent.CountDownLatch;

public class CounterMainSync {
	
	static class Counter {
		
		private int count = 0;
		private	CountDownLatch countDownLatch;	//进行线程阻塞
		
		public Counter(CountDownLatch countDownLatch) {
			super();
			this.countDownLatch = countDownLatch;
		}

		public void incr() {
			synchronized (this) {
				try {
					//为了使效果明显，线程沉睡1毫秒
					Thread.sleep(1);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				count ++;
				countDownLatch.countDown();
			}
		}
		
		public int getCount() {
			return count;
		}
		
	}
	
	public static void main(String[] args) {
		//同时启动1000个线程，去进行i++计算，看看实际结果
		CountDownLatch countDownLatch = new CountDownLatch(1000);
		final Counter counter = new Counter(countDownLatch);
		for(int i = 0; i < 1000; i++) {
			new Thread(new Runnable() {
				
				@Override
				public void run() {
					counter.incr();
				}
			}).start();
		}
		try {
			countDownLatch.await();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		System.out.println(counter.getCount());
	}
}
